<template>
  <!--dialog1-->
  <!-- <el-dialog v-model="dialogTableVisible1" :show-close="false" align-center width="60%">
    <div style="height: 500px; overflow: hidden">
      <div style="position: absolute; top: 2vh">
        <el-input
          style="width: 30%; margin-left: 2px"
          v-model="testName"
          placeholder="测试名称"
        >
          <template #prefix>
            <el-icon class=""><search /></el-icon>
          </template>
        </el-input>
        <el-input
          style="width: 30%; margin-left: 2px"
          v-model="testNumber"
          placeholder="测试数字"
        >
          <template #prefix>
            <el-icon class=""><search /></el-icon>
          </template>
        </el-input>
        <el-button style="margin-left: 5px" @click="searchKh" type="primary"
          >查询</el-button
        >
      </div>
      <el-table
        border
        stripe
        :data="tableData1"
        style="width: 100%"
        @row-click="RowClick1"
        :cell-style="cellStyle"
        :header-cell-style="headerCellStyle"
        max-height="470px"
        height="470px"
      >
        <el-table-column prop="index" label="Id" width="180" />
        <el-table-column prop="testName" label="测试名称" width="180" />
        <el-table-column prop="testNumber" label="测试数字" />
      </el-table>
      <div class="demo-pagination-block">
        <el-pagination
          :current-page="page1"
          :page-size="limit1"
          :page-sizes="[100, 200, 300, 400]"
          :small="small"
          :disabled="disabled"
          :background="background"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total1"
          @size-change="handleSizeChange1"
          @current-change="handleCurrentChange1"
        />
      </div>
    </div>
  </el-dialog> -->
  <!--dialog3-->
  <!-- <el-dialog v-model="dialogTableVisible3" :show-close="true" align-center width="60%">
    <div style="height: 500px; overflow: hidden">
      <div style="position: absolute; top: 2vh">
        <el-input
          style="width: 30%; margin-left: 2px"
          v-model="testName"
          placeholder="测试名称"
        >
          <template #prefix>
            <el-icon class=""><search /></el-icon>
          </template>
        </el-input>
        <el-input
          style="width: 30%; margin-left: 2px"
          v-model="testNumber"
          placeholder="测试数字"
        >
          <template #prefix>
            <el-icon class=""><search /></el-icon>
          </template>
        </el-input>

        <el-button
          style="margin-left: 0px"
          @click="searchYwy"
          v-if="searchYwyPermissions8"
          type="primary"
          >查询</el-button
        >
        <el-button
          style="margin-left: 2px"
          @click="updatYwy"
          v-if="updatYwyPermissions8"
          type="success"
          >更新测试名称</el-button
        >
      </div>
      <div class="dialogDiv">
        <el-table
          border
          stripe
          :data="tableData3"
          @row-click="RowClick3"
          :cell-style="cellStyle"
          :header-cell-style="headerCellStyle"
          max-height="470px"
          height="470px"
        >
          <el-table-column prop="index" label="Id" width="60" align="center" />
          <el-table-column prop="testName" label="测试名称" />
          <el-table-column prop="testNumber" label="测试数字" width="180" />
        </el-table>
        <div class="demo-pagination-block">
          <el-pagination
            :current-page="page3"
            :page-size="limit3"
            :page-sizes="[100, 200, 300, 400]"
            :small="small"
            :disabled="disabled"
            :background="background"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total3"
            @size-change="handleSizeChange3"
            @current-change="handleCurrentChange3"
          />
        </div>
      </div>
    </div>
  </el-dialog> -->
  <!--dialog4-->
  <!-- <el-dialog v-model="dialogTableVisible4" :show-close="true" align-center width="60%">
    <div style="height: 500px; overflow: hidden">
      <div style="position: absolute; top: 2vh"> -->
  <!-- inputK3Bm -->
  <!-- <el-input
          style="width: 30%; margin-left: 2px"
          v-model="testName"
          placeholder="测试名称"
        >
          <template #prefix>
            <el-icon class=""><search /></el-icon>
          </template>
        </el-input>
        <el-input
          style="width: 30%; margin-left: 2px"
          v-model="testNumber"
          placeholder="测试数字"
        >
          <template #prefix>
            <el-icon class=""><search /></el-icon>
          </template>
        </el-input>
        <el-button style="margin-left: 0px" @click="searcpyt" type="primary"
          >查询</el-button
        >
      </div>
      <div class="dialogDiv">
        <el-table
          border
          stripe
          :data="tableData4"
          @row-click="RowClick4"
          :cell-style="cellStyle"
          :header-cell-style="headerCellStyle"
          max-height="470px"
          height="470px"
        >
          <el-table-column prop="testName" label="测试名称" width="60" align="center" />
          <el-table-column prop="testNumber" label="测试数字" />
        </el-table>
        <div class="demo-pagination-block">
          <el-pagination
            :current-page="page4"
            :page-size="limit4"
            :page-sizes="[10, 20, 30, 40]"
            :small="small"
            :disabled="disabled"
            :background="background"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total4"
            @size-change="handleSizeChange4"
            @current-change="handleCurrentChange4"
          />
        </div>
      </div>
    </div>
  </el-dialog> -->
  <!--dialog5-->
  <el-dialog v-model="dialogTableVisible5" :show-close="true" align-center width="60%">
    <div style="height: 465px; overflow: hidden">
      <div style="position: absolute; top: 5px">
        <!-- inputK3Bm -->
        <el-input
          style="width: 30%; margin-left: 2px"
          v-model="testName"
          placeholder="测试名称"
        >
          <template #prefix>
            <el-icon class=""><search /></el-icon>
          </template>
        </el-input>
        <el-input
          style="width: 30%; margin-left: 2px"
          v-model="testNumber"
          placeholder="测试数字"
        >
          <template #prefix>
            <el-icon class=""><search /></el-icon>
          </template>
        </el-input>

        <el-button
          style="margin-left: 0px"
          @click="searbzfa"
          v-if="searbzfaPermissions8"
          type="primary"
          >查询</el-button
        >
      </div>

      <div class="dialogDiv">
        <el-table
          border
          stripe
          :data="tableData5"
          @row-click="RowClick5"
          :cell-style="cellStyle"
          :header-cell-style="headerCellStyle"
          max-height="470px"
          height="470px"
        >
          <el-table-column fixed type="index" width="60" align="center" />
          <el-table-column prop="testName" label="测试名称" width="120" align="center" />
          <el-table-column
            prop="testNumber"
            label="测试数字"
            width="120"
            align="center"
          />
        </el-table>
        <div class="demo-pagination-block">
          <el-pagination
            :current-page="page5"
            :page-size="limit5"
            :page-sizes="[10, 20, 30, 40]"
            :small="small"
            :disabled="disabled"
            :background="background"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total5"
            @size-change="handleSizeChange5"
            @current-change="handleCurrentChange5"
          />
        </div>
      </div>
    </div>
  </el-dialog>
  <!-- 添加 -->
  <div
    v-if="dialogTableVisible"
    :fullscreen="false"
    :modal="false"
    :show-close="false"
    :width="screenWidth + 20 + 'px'"
    :append-to-body="true"
    style="
      position: absolute;
      left: 6rem;
      margin-top: 42px;
      z-index: 10;
      background-color: white;
    "
    :close-on-click-modal="false"
  >
    <div :style="{ width: screenWidth + 'px' }">
      <div
        :style="{
          height: '40px',
          borderBottom: '1px solid #ccc',
          width: '100%',
        }"
      >
        <div style="position: absolute; right: 15px">
          <!-- <el-button v-if="Permission" @click="upButton" type="primary">
            修改业务员</el-button
          > -->
          <el-button @click="addRow" v-if="addRowPermissions8" type="primary"
            >增行</el-button
          >
          <el-button
            @click="getDeleteRowData"
            v-if="getDeleteRowDataPermissions8"
            type="danger"
            >删除</el-button
          >
          <el-button
            type="primary"
            @click="insertMaterialsFixed"
            v-if="showInsertButton && insertMaterialsFixedPermissions8"
            >保存</el-button
          >
          <el-button
            type="primary"
            @click="updateMaterialsFixed"
            v-if="!showInsertButton && updateMaterialsFixedPermissions8"
            >保存</el-button
          >
          <el-button
            @click="OFFdialogTableVisible"
            v-if="OFFdialogTableVisiblePermissions8"
            type="danger"
            >关闭</el-button
          >
        </div>
      </div>
      <!-- <div class="vertical-line2"></div>
    <div class="vertical-line4"></div> -->
      <!-- title -->
      <div
        ref="titleDiv"
        :style="{
          backgroundColor: 'rgba(247, 247, 247, 0.903)',
          height: inputHeight - 30 + 'px',
          width: screenWidth + 'px',
        }"
      >
        <el-form :model="form" class="demo-form-inline" :inline="true">
          <el-form-item class="labs" style="margin-right: 0">
            <label class="lab" style="width: 100px; padding-right: 5px">测试名称</label>
            <el-input
              style="width: 180px"
              v-model="form.testName"
              placeholder="测试名称"
              :readonly="true"
              disabled
              clearable
            />
          </el-form-item>
          <el-form-item class="labs" style="margin-right: 0">
            <label class="lab" style="width: 100px; padding-right: 5px">
              <span style="color: red">*</span>单据日期</label
            >
            <el-config-provider :locale="locale">
              <el-date-picker
                style="width: 180px"
                v-model="form.djrq"
                type="date"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                placeholder="单据日期"
              />
            </el-config-provider>
            <el-form-item class="labs" style="margin-right: 0">
              <label class="lab" style="width: 100px; padding-right: 5px">
                <span style="color: red">*</span>方案</label
              >
              <!-- <el-input
                style="width: 180px"
                v-model="form.testNumber"
                placeholder="请选择测试数字"
                :readonly="true"
                clearable
                @click="windowBzfa"
              /> -->
              <DropDown
                :columns="[
                  { prop: 'testName', label: '测试名称', minWidth: '50' },
                  { prop: 'testNumber', label: '测试数字', minWidth: '50' },
                ]"
                :keywords="{ label: 'testName', value: 'testName' }"
                :api-url="'/select/test'"
                @row-selected="onRowSelected"
              />
            </el-form-item>
          </el-form-item>
        </el-form>
      </div>
      <!-- 子表添加 -->
      <table-component-2
        :columns="formColumns"
        :formInline="formInline"
        :formDataList="formDataList"
        :addRow="addRow"
        :handleDeletes="handleDeletes"
      />

      <!-- <el-form :inline="true" :model="formInline">
        <div
          :style="{
            width: screenWidth + 'px',
            'max-height': tableHeight + 'px',
            'overflow-y': 'auto',
            'overflow-x': 'hidden',
            'scrollbar-width': 'thin',
          }"
        >
          <table>
            <tr class="sticky-header" style="z-index: 99">
              <th style="width: 50px" class="table-header">序号</th>
              <th style="width: 50px" class="table-header">
                <el-checkbox @change="toggleSelectAll" v-model="selectAll"></el-checkbox>
              </th>
              <th style="width: 150px" class="table-header">测试名称</th>
              <th style="width: 150px" class="table-header">测试数字</th>
              <th style="width: 80px" class="table-header">操作</th>
            </tr>
            <tr v-for="(formData, index) in formDataList" :key="index">
              <td style="text-align: center">{{ index + 1 }}</td>
              <td style="text-align: center">
                <el-checkbox v-model="formData.selected"></el-checkbox>
              </td>
              <td class="table-value" style="width: 100px; text-align: center">
                <div>{{ formData.testName }}</div>
              </td>
              <td class="table-value" style="width: 100px; text-align: center">
                <div>{{ formData.testNumber }}</div>
              </td>
              <td>
                <el-button
                  style="height: 30px; margin-top: 1px"
                  type="danger"
                  @click="handleDeletes(index)"
                  >删除</el-button
                >
              </td>
            </tr> -->

      <!-- 合计行 -->
      <!-- <tr
              style="
                text-align: center;
                position: sticky;
                bottom: -1px;
                background-color: #ddd;
                z-index: 99;
              "
            > -->
      <!-- <td colspan="9">合计：</td> -->
      <!-- <td>合计:</td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
            </tr>
          </table>
        </div>
      </el-form> -->
      <div style="background-color: rgba(247, 247, 247, 0.903)">
        <el-form
          :model="form"
          class="demo-form-inline"
          :inline="true"
          :style="{
            backgroundColor: ' rgba(247, 247, 247, 0.903)',
            width: screenWidth - 10 + 'px',
            height: '120px',
          }"
        >
          <el-form-item class="lab" style="margin-right: 0">
            <el-input
              :style="{
                width: '180vh',
                zIndex: '99',
                backgroundColor: '#ffffff',
                resize: 'none',
                height: '50px',
              }"
              type="textarea"
              v-model="form.bz"
              placeholder="备注"
              clearable
            />
          </el-form-item>
          <el-form-item class="labs" style="margin-right: 0">
            <label class="lab" style="width: 100px; padding-right: 5px">制单人</label>
            <el-input
              v-model="form.zdr"
              style="width: 200px; height: 3.5vh"
              disabled
              placeholder="制单人"
              clearable
            />
          </el-form-item>
          <el-form-item class="labs" style="margin-right: 0">
            <label class="lab" style="width: 100px; padding-right: 5px">制单时间</label>
            <el-config-provider :locale="locale">
              <el-date-picker
                style="width: 200px"
                disabled
                v-model="form.zdsj"
                type="datetime"
                placeholder="制单时间"
              />
            </el-config-provider>
          </el-form-item>
          <el-form-item class="labs" style="margin-right: 0">
            <label class="lab" style="width: 100px; padding-right: 5px">修改人</label>
            <el-input
              style="width: 180px"
              v-model="form.xgr"
              disabled
              placeholder="修改人"
              clearable
            />
          </el-form-item>
          <el-form-item class="labs" style="margin-right: 0">
            <label class="lab" style="width: 100px; padding-right: 5px">修改时间</label>
            <el-config-provider :locale="locale">
              <el-date-picker
                style="width: 200px"
                disabled
                v-model="form.xgsj"
                type="datetime"
                placeholder="修改时间"
              />
            </el-config-provider>
          </el-form-item>
          <el-form-item class="labs" style="margin-right: 0">
            <label class="lab" style="width: 100px; padding-right: 5px">审核人</label>
            <el-input
              style="width: 200px"
              v-model="form.shr"
              disabled
              placeholder="审核人"
              clearable
            />
          </el-form-item>
          <el-form-item class="labs" style="margin-right: 0; heiht: 3.5vh">
            <label class="lab" style="width: 100px; padding-right: 5px">审核时间:</label>
            <el-config-provider :locale="locale">
              <el-date-picker
                style="width: 200px"
                disabled
                v-model="form.shsj"
                type="datetime"
                placeholder="审核时间"
              />
            </el-config-provider>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
  <!-- 页面布局 -->
  <div>
    <el-container>
      <el-header height="65px" :style="{ 'border-bottom': '1px solid #ccc' }">
        <!-- 头部按钮 -->
        <el-row type="flex" justify="end" style="background-color: rgb(211, 227, 253)">
          <div style="display: flex; align-items: center">
            <el-button
              @click="searchButton"
              v-if="searchButtonPermissions8"
              type="primary"
            >
              查询</el-button
            >
            <el-button
              @click="handleAction1"
              v-if="handleAction1Permissions8"
              type="success"
              >新增</el-button
            >
            <el-button @click="printPage" v-if="searchButtonPermissions8" type="primary">
              打印</el-button
            >
            <el-button
              @click="exportSelectedData"
              v-if="searchButtonPermissions8"
              type="primary"
            >
              导出</el-button
            >
            <el-button
              @click="handleWarning0"
              v-if="handleWarning0Permissions8"
              type="warning"
              >审核</el-button
            >
            <el-button
              @click="handleAction1"
              v-if="handleAction1Permissions8"
              type="success"
              >新增</el-button
            >
            <el-button @click="printPage" v-if="searchButtonPermissions8" type="primary">
              打印</el-button
            >
            <el-button
              @click="downloadFile"
              v-if="handleWarning0Permissions8"
              type="primary"
              >下载文件</el-button
            >
            <el-button @click="deleteFile" v-if="handleWarning0Permissions8" type="danger"
              >删除文件</el-button
            >
            <el-upload
              v-model:file-list="fileList"
              class="upload-demo"
              multiple
              :on-exceed="handleExceed"
              :before-upload="beforeUpload"
              action="http://192.168.10.2:8081/upload"
              :on-success="handleSuccess"
              :show-file-list="false"
            >
              <el-button type="primary">上传文件</el-button>
            </el-upload>
            <!-- <el-button
              @click="exportToPdf"
              v-if="handleWarning1Permissions8"
              type="danger"
              >PDF</el-button
            >
            <el-button @click="handleDelete" v-if="handleDeletePermissions8" type="danger"
              >删除</el-button
            > -->
            <!-- <el-button style="height: 4vh" @click="handleAction2" type="success"
              >增加定义</el-button
            > -->
          </div>
          <!-- <div class="title">包材需求计算</div> -->
        </el-row>
        <div
          style="margin-left:5.6rem;height: 30px;width=100%; background:rgb(241,244,243);margin-bottom: 0;position: relative; display: flex; justify-content: flex-start;"
        >
          <el-input
            style="width: 10%; height: 25px; margin-left: 2px; margin-top: 2px"
            v-model="testName"
            placeholder="测试名称"
          >
            <template #prefix>
              <el-icon class=""><search /></el-icon>
            </template>
          </el-input>
          <el-input
            style="width: 10%; height: 25px; margin-left: 2px; margin-top: 2px"
            v-model="testNumber"
            placeholder="测试数字"
          >
            <template #prefix>
              <el-icon class=""><search /></el-icon>
            </template>
          </el-input>
        </div>
      </el-header>
      <el-container>
        <el-container>
          <el-main
            class="print-template"
            style="padding: 2px 2px 0 2px; margin-left: 5.6rem"
          >
            <table-component
              :columns="tableColumns"
              :data="tableData"
              @selection-change="handleSelectionChange"
              @row-click="RowClick"
            />
            <div class="demo-pagination-block" v-if="isPrinting">
              <el-pagination
                v-model:current-page="page"
                v-model:page-size="limit"
                :page-sizes="[50, 500, 1000, 1500, 2000, 8000]"
                :small="true"
                :background="true"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </div>
          </el-main>
          <!-- <el-footer style="background: linear-gradient(to right, #f9f9fc, #fef5f0)"
            >Footer</el-footer
          > -->
        </el-container>
        <!-- <el-aside width="20%"></el-aside> -->
      </el-container>
    </el-container>
  </div>
</template>

<script setup lang="ts">
import {
  ref,
  watch,
  reactive,
  onMounted,
  onBeforeMount,
  computed,
  nextTick,
  onUnmounted,
  toRefs,
} from "vue";
import { Delete, Edit, Search, Share, Upload, Calendar } from "@element-plus/icons-vue";
import {
  ElTable,
  TableColumnCtx,
  ElButton,
  ElDialog,
  dialogEmits,
  ElMessage,
  FormRules,
  FormInstance,
} from "element-plus";
import { CircleCloseFilled } from "@element-plus/icons-vue";
import { useRouter } from "vue-router";
import axios from "../../axios/axiosInstance";
import Cookies from "js-cookie";
import { format } from "date-fns";
import * as XLSX from "xlsx";
// import * as jsPDF from 'jspdf';
import jsPDF from "jspdf";
import "jspdf-autotable";
import TableComp from "../../components/table/TableComponent.vue";
import TableComp2 from "../../components/table/TableComponent2.vue";
import DropDown from "../../components/table/DropDown.vue";
// 日期中文
import zhCn from "element-plus/dist/locale/zh-cn.mjs";
const Permission = ref(false);
const isDdslDisabledYwy = ref(true);
const router = useRouter();
const isDdslDisabled = ref(true);
// 权限控制
const searbzfaPermissions8 = ref(false);
const searchYwyPermissions8 = ref(false);
const updatYwyPermissions8 = ref(false);
const addRowPermissions8 = ref(false);
const getDeleteRowDataPermissions8 = ref(false);
const insertMaterialsFixedPermissions8 = ref(false);
const updateMaterialsFixedPermissions8 = ref(false);
const OFFdialogTableVisiblePermissions8 = ref(false);
const searchButtonPermissions8 = ref(false);
const handleAction1Permissions8 = ref(false);
const handleWarning0Permissions8 = ref(false);
const handleWarning1Permissions8 = ref(false);
const handleDeletePermissions8 = ref(false);
const menuId = ref(8);
const buttonVariables = {
  searbzfaPermissions8,
  searchYwyPermissions8,
  updatYwyPermissions8,
  addRowPermissions8,
  getDeleteRowDataPermissions8,
  insertMaterialsFixedPermissions8,
  updateMaterialsFixedPermissions8,
  OFFdialogTableVisiblePermissions8,
  searchButtonPermissions8,
  handleAction1Permissions8,
  handleWarning0Permissions8,
  handleWarning1Permissions8,
  handleDeletePermissions8,
};
const selectPermissionsButton = () => {
  const userName = Cookies.get("userName");

  axios({
    url: "/select/Permissions/Button",
    method: "post",
    data: {
      userName: userName,
      menuId: menuId.value,
    },
  }).then((res) => {
    res.data.forEach((button) => {
      const buttonName = button.buttonName;
      if (buttonVariables.hasOwnProperty(buttonName)) {
        buttonVariables[buttonName].value = true;
      }
    });
  });
};
selectPermissionsButton();
// 计算高度
const screenHeight = ref(null);
const dynamicHeight = ref(null);
const dynamicHeightYtfl = ref(null);
const tableHeight = ref(null);

const getScreenHeight = () => {
  console.log(window.innerHeight);
  screenHeight.value = window.innerHeight - 146;
  dynamicHeight.value = `${window.innerHeight - 55}px`;
  dynamicHeightYtfl.value = window.innerHeight - 120;
  tableHeight.value = window.innerHeight - 435 + 19;
  console.log("高度" + window.innerHeight);
  console.log("子表:" + tableHeight.value);
};
getScreenHeight();
const handleSelectionChange = (val) => {
  selectedRows.value = val;
};
const activeIndex = ref("1");
const handleSelect = (key: string, keyPath: string[]) => {};
const dialogTableVisible = ref(false);
const dialogTableVisible1 = ref(false);
const dialogTableVisible2 = ref(false);
const dialogTableVisible3 = ref(false);
const dialogTableVisible4 = ref(false);
const dialogTableVisible5 = ref(false);
//声明类
const formInline = ref([]);
const ddslinput = ref(null);
const isPrinting = ref(false);
const formColumns = ref([
  { prop: "testName", label: "测试名称", width: "150px", align: "center" },
  { prop: "testNumber", label: "测试数字", width: "150px", align: "center" },
  { type: "input", label: "输入框", width: "150px", align: "center" },
  { type: "button", label: "操作框", width: "100px", align: "center" },
]);
const tableColumns = ref([
  { type: "index", width: "50", align: "center", fixed: "left" },
  { prop: "id", label: "id", width: "60", align: "center", fixed: "left" },
  { prop: "fileName", label: "文件名", width: "120", align: "center", fixed: "left" },
  { prop: "fileType", label: "文件类型", width: "120", align: "center" },
  { prop: "formattedFileSize", label: "文件大小", width: "90", align: "center" },
  { prop: "uploader", label: "上传人", width: "120", align: "center" },
  { prop: "filePath", label: "上传路径", width: "120", align: "center" },
  { prop: "uploadTime", label: "上传时间", width: "120", align: "center" },
  { type: "selection", width: "50", align: "center" },
]);
const selectedRows = ref([]);
const testName = ref("");
const testNumber = ref("");
const fileType = ref("");
const fileSize = ref("");
const uploadTime = ref("");
const uploader = ref("");
const fileName = ref("");
const filePath = ref("");
const uploadDir = ref("");
const formattedFileSize = ref("");
const verticalLine3 = ref(null);
const tableData = ref([]);
const tableData1 = ref([]);
const tableData3 = ref([]);
const tableData4 = ref([]);
const tableData5 = ref([]);
const checkList = ref([]);
const checkList1 = ref([]);
const showInsertButton = ref(true);
const screenWidth = ref(window.innerWidth);
const inputHeight = ref(200);
// 头部按钮
const table = ref();
const rowTable = ref([]);
//子表
let selectedRowIndex = -1; // 初始化为-1，表示没有选中的行
let clearSelection = true;
//多选
const selectAll = ref(false);
// 分页
const page = ref(1);
const page1 = ref(1);
const page2 = ref(1);
const page3 = ref(1);
const page4 = ref(1);
const page5 = ref(1);
const limit = ref(50);
const limit1 = ref(50);
const limit2 = ref(50);
const limit3 = ref(50);
const limit4 = ref(50);
const limit5 = ref(50);
const total = ref(10);
const total1 = ref(10);
const total2 = ref(10);
const total3 = ref(10);
const total4 = ref(10);
const total5 = ref(10);
const loading = ref(false);
// // 设置表头样式
// const headerCellStyle = {
//   // E9E9E7
//   borderColor: "#B9C9C7",
//   backgroundColor: "#F2F4FA", // 表头背景颜色
//   fontWeight: "bold", // 表头文字粗细
//   color: "#1F2129",
//   // padding: "0 0 0 30px",
// };
//方法类
const selectCookies = () => {};
selectCookies();
const handleResize = () => {
  screenWidth.value = window.innerWidth;
  console.log("宽度" + screenWidth.value);
  screenWidth.value = screenWidth.value - 96;
  inputHeight.value = 100;
};
handleResize();
const handleRowClick = (row) => {
  isDdslDisabled.value = false;
  isDdslDisabledYwy.value = true;
  dialogTableVisible.value = true;
  showInsertButton.value = false;
  form.testName = row.testName;
  form.testNumber = row.testNumber;
  const userName = Cookies.get("userName");
  const currentFormattedDateTime = getCurrentFormattedDateTime();
  const currentFormattedDate = getCurrentFormattedDate();
  form.xgsj = currentFormattedDateTime;
  form.xgr = userName;
  // 回显测算类型
  // checkList
  // checkList.value = row.cslx.split(",");
  // checkList1.value = row.csfs.split(",");
  // 回显子表
  axios({
    url: "/select/test",
    method: "post",
    data: {
      id: row.id,
    },
  }).then((res) => {
    const testList = res.data;
    if (testList == 0) {
      for (let a = 0; a < 21; a++) {
        addRow();
      }
      return;
    }
    const formattedData = testList.map((test, index) => ({
      testName: test.testName,
      testNumber: test.testNumber,
      selected: false,
    }));
    formDataList.value = formattedData;
    console.log(formDataList.value);
    for (let a = 0; a < 21; a++) {
      addRow();
    }
  });
};
const handleAction1 = () => {
  dialogTableVisible.value = true;
  isDdslDisabled.value = true;
  isDdslDisabledYwy.value = false;
  showInsertButton.value = true;
  const userName = Cookies.get("userName");
  form.zdr = userName;
  // for (let a = 0; a < 21; a++) {
  //   addRow();
  // }

  const currentFormattedDateTime = getCurrentFormattedDateTime();
  const currentFormattedDate = getCurrentFormattedDate();
  form.zdsj = currentFormattedDateTime;
  Permission.value = true;
  // console.log(1);
  axios({
    url: "/select/test2",
    method: "post",
    data: {
      // userName: userName,
      page: page.value,
      limit: limit.value,
    },
  }).then((res) => {
    tableData5.value = res.data;
    console.log(tableData5.value);
    // dialogTableVisible5.value = true;
    //   testName.value = res.data.name;
    //   testName.value = userName;
    //  testNumber.value=res.data.testNumber;
  });
  // if (userName == "0" || userName == "admin") {
  //   nextTick(() => {
  //     dialogTableVisible3.value = true;
  //   });
  // }
};

// 关闭弹窗
const OFFdialogTableVisible = () => {
  dialogTableVisible.value = false;
  showInsertButton.value = true;

  Object.keys(form).forEach((key) => {
    form[key] = "";
  });
  (checkList.value = ""), (checkList1.value = "");
  // 删除
  formDataList.value = [];
  // location.reload();
  page1.value = 1;
  page2.value = 1;
  page3.value = 1;
  page4.value = 1;
  page5.value = 1;
  limit1.value = 50;
  limit2.value = 50;
  limit3.value = 50;
  limit4.value = 50;
  limit5.value = 50;
};
// 进入页面
const selectpurposes = () => {
  // 查看是否登录
  const userName = Cookies.get("userName");
  if (!userName) {
    router.push("/");
    return;
  }
  axios({
    url: "/select/upload",
    method: "post",
    data: {
      fileType: fileType.value,
      fileSize: fileSize.value,
      uploadTime: uploadTime.value,
      uploader: uploader.value,
      fileName: fileName.value,
      filePath: filePath.value,
      formattedFileSize: formattedFileSize.value,
      uploadDir: uploadDir.value,
      page: page.value,
      limit: limit.value,
    },
  }).then((res) => {
    const testList = res.data;
    if (testList.length == 0) {
      loading.value = false;
      return;
    }
    total.value = res.data[0].total;

    tableData.value = testList.map((test) => ({
      // 根据 djzt 的值设置状态
      // zt: test.zt === 0 ? "待审" : "已审核",
      id: test.id,
      fileType: test.fileType,
      fileSize: test.fileSize,
      uploadTime: test.uploadTime,
      uploader: test.uploader,
      fileName: test.fileName,
      filePath: test.filePath,
      formattedFileSize: test.formattedFileSize,
      uploadDir: test.uploadDir,
    }));

    for (let a = 0; a < 20; a++) {
      addRow();
    }
    //制单人
    form.zdr = userName;
    // 制单时间
    const currentFormattedDateTime = getCurrentFormattedDateTime();
    const currentFormattedDate = getCurrentFormattedDate();
    form.zdsj = currentFormattedDateTime;
    loading.value = false;
  });
  loading.value = true;
};

const RowClick1 = (row, selection) => {
  form.testName = row.testName;
  dialogTableVisible1.value = false;
};
const formDataList = ref([
  {
    testName: "",
    testNumber: "",
    selected: false,
    issl: false,
    isdj: false,
  },
]);
const form = reactive({
  testName: "",
  testNumber: "",
  zdr: "",
  zdsj: "",
  xgr: "",
  xgsj: "",
  shr: "",
  shsj: "",
});
const addRow = () => {
  formDataList.value.push({
    testName: "",
    testNumber: "",
    selected: false,
    issl: false,
    isdj: false,
  });
};
var indexK3bm = 0;
const openWlbm = (index) => {
  indexK3bm = index;
  dialogTableVisible2.value = true;
};
const RowClick2 = (row, selection) => {
  for (let i = 0; i < formDataList.value.length; i++) {
    if (formDataList.value[i].testName === row.testName) {
      const duplicateRowIndex = i + 1; // 行数从1开始
      ElMessage.error(`第 ${duplicateRowIndex} 行已经存在相同的物料编码:${row.testName}`);
      return;
    }
  }
  formDataList.value[indexK3bm].testName = row.testName;
  formDataList.value[indexK3bm].testNumber = row.testNumber;
  dialogTableVisible2.value = false;
};
const RowClick3 = (row) => {
  testName.value = row.testName;
  testNumber.value = row.testNumber;
  form.testName = row.testName;
  form.testNumber = row.testNumber;
  dialogTableVisible3.value = false;
  dialogTableVisible5.value = true;
};
const RowClick4 = (row) => {
  form.testName = row.testName;
  dialogTableVisible4.value = false;
};
const onRowSelected = (selectedRow) => {
  formDataList.value = [selectedRow];
};
const RowClick5 = (row) => {
  isDdslDisabled.value = false;
  form.testName = row.testName;
  form.testNumber = row.testNumber;
  // formDataList.value = row;
  formDataList.value.splice(0, 1, row);
  dialogTableVisible5.value = false;
};
// axios({
//   url: "/select/test",
//   method: "post",
//   data: {
//     id: row.id,
//   },
// }).then((res) => {
//   const testList = res.data;
//   if (testList == 0) {
//     for (let a = 0; a < 21; a++) {
//       addRow();
//     }
//     return;
//   }
//   const formattedData = testList.map((test, index) => ({
//     testName: test.testName,
//     testNumber: test.testNumber,
//     selected: false,
//   }));
//   formDataList.value = formattedData;
//   for (let a = 0; a < 21; a++) {
//     addRow();
//   }
// });
// ddslinput.value.focus();

const windowBzfa = () => {
  dialogTableVisible5.value = true;
};
const cellStyle = ({ row, column, rowIndex, columnIndex }) => {
  if (selectedRows.value.find((selectedRow) => selectedRow.id === row.id)) {
    return {
      backgroundColor: "#DFF0DB !important",
      borderColor: "#B9C9C7",
      padding: "4px",
    };
  } else {
    // #E9E9E7
    // D9D9D7   C9C9C7 A9A9A7
    return { borderColor: "#B9C9C7", padding: "4px", margin: 0 };
  }
};
// const rowState = (arg) => {
//   return {
//     height: "20px", // 设置合适的行高值
//     fontSize: "12px", // 设置合适的字体大小值
//     // color: "black",
//   };
// };
// 查询
const searchButton = () => {
  loading.value = true;
  tableData.value = [];
  nextTick(() => {
    const userName = Cookies.get("userName");
    axios({
      url: "/select/test",
      method: "post",
      data: {
        testName: testName.value,
        testNumber: testNumber.value,
        page: page.value,
        limit: limit.value,
      },
    }).then((res) => {
      const testList = res.data;
      if (testList.length == 0) {
        loading.value = false;
        total.value = 0;
        return;
      }
      total.value = res.data[0].total;

      tableData.value = testList.map((test) => ({
        // 根据 djzt 的值设置状态
        zt: test.zt === 0 ? "待审" : "已审核",
        autoId: test.autoId,
        testName: test.testName,
        testNumber: test.testNumber,
      }));

      for (let a = 0; a < 20; a++) {
        addRow();
      }
      //制单人
      form.zdr = userName;
      // 制单时间
      const currentFormattedDateTime = getCurrentFormattedDateTime();
      const currentFormattedDate = getCurrentFormattedDate();
      form.zdsj = currentFormattedDateTime;
      // form.djrq = currentFormattedDate;
      loading.value = false;
    });
  });
  loading.value = true;
};
const searchYwy = () => {
  axios({
    url: "/select/test",
    method: "post",
    data: {
      testName: testName.value,
      testNumber: testNumber.value,
      page: page3.value,
      limit: limit3.value,
    },
  }).then((res) => {
    tableData3.value = res.data;
    if (res.data.length == 0) {
      total3.value = 0;
      return;
    }
    total3.value = res.data[0].total;
  });
};
const getYwy = () => {
  axios({
    // url: "/get/ywy",
    url: "/get/Search/ywy",
    method: "post",
    data: {
      testName: testName.value,
      testNumber: testNumber.value,
      page: page3.value,
      limit: limit3.value,
    },
  }).then((res) => {
    tableData3.value = res.data;
    if (res.data.length == 0) {
      total3.value = 0;
      return;
    }
    total3.value = res.data[0].total;
  });
};
const searcpyt = () => {
  axios({
    url: "/select/test",
    method: "post",
    data: {
      testName: testName.value,
      testNumber: testNumber.value,
      page: page4.value,
      limit: limit4.value,
    },
  }).then((res) => {
    tableData4.value = res.data;
    if (res.data.length == 0) {
      return;
    }
    total4.value = res.data[0].total;
  });
};
const searbzfa = () => {
  axios({
    url: "/select/test2",
    method: "post",
    data: {
      testName: testName.value,
      testNumber: testNumber.value,
      page: page5.value,
      limit: limit5.value,
    },
  }).then((res) => {
    const testList = res.data;
    tableData5.value = testList.map((test) => ({
      // 根据 djzt 的值设置状态
      // 根据 djzt 的值设置状态
      zt: test.djzt === 0 ? "待审" : "已审核",
      id: test.id,
      testName: test.testName,
      testNumber: test.testNumber,
    }));
    if (testList.length == 0) {
      total5.value = 0;
      return;
    }
    total5.value = res.data[0].total;
  });
};
const handleSizeChange = (val: number) => {
  loading.value = true;
  tableData.value = [];
  nextTick(() => {
    const userName = Cookies.get("userName");
    axios({
      url: "/select/upload",
      method: "post",
      data: {
        fileType: fileType.value,
        fileSize: fileSize.value,
        uploadTime: uploadTime.value,
        uploader: uploader.value,
        fileName: fileName.value,
        filePath: filePath.value,
        uploadDir: uploadDir.value,
        formattedFileSize: formattedFileSize.value,
        page: page.value,
        limit: limit.value,
      },
    }).then((res) => {
      const testList = res.data;
      if (testList.length == 0) {
        loading.value = false;
        return;
      }
      total.value = res.data[0].total;

      tableData.value = testList.map((test) => ({
        // 根据 djzt 的值设置状态
        zt: test.zt === 0 ? "待审" : "已审核",
        autoId: test.autoId,
        testName: test.fabh,
        testNumber: test.testNumber,
      }));

      for (let a = 0; a < 20; a++) {
        addRow();
      }
      //制单人
      form.zdr = userName;
      // 制单时间
      const currentFormattedDateTime = getCurrentFormattedDateTime();
      const currentFormattedDate = getCurrentFormattedDate();
      form.zdsj = currentFormattedDateTime;
      loading.value = false;
    });
  });
  loading.value = true;
};
const handleCurrentChange = (val: number) => {
  loading.value = true;
  tableData.value = [];
  nextTick(() => {
    const userName = Cookies.get("userName");
    axios({
      url: "/select/upload",
      method: "post",
      data: {
        fileType: fileType.value,
        fileSize: fileSize.value,
        uploadTime: uploadTime.value,
        uploader: uploader.value,
        fileName: fileName.value,
        filePath: filePath.value,
        uploadDir: uploadDir.value,
        formattedFileSize: formattedFileSize.value,
        page: page.value,
        limit: limit.value,
      },
    }).then((res) => {
      const testList = res.data;
      if (testList.length == 0) {
        loading.value = false;
        return;
      }
      total.value = res.data[0].total;

      tableData.value = testList.map((test) => ({
        // 根据 djzt 的值设置状态
        zt: test.zt === 0 ? "待审" : "已审核",
        autoId: test.autoId,
        testName: test.fabh,
        testNumber: test.testNumber,
      }));

      for (let a = 0; a < 20; a++) {
        addRow();
      }
      //制单人
      form.zdr = userName;
      // 制单时间
      const currentFormattedDateTime = getCurrentFormattedDateTime();
      const currentFormattedDate = getCurrentFormattedDate();
      form.zdsj = currentFormattedDateTime;
      // form.djrq = currentFormattedDate;
      loading.value = false;
    });
  });
  loading.value = true;
};
const handleSizeChange1 = (val: number) => {
  axios({
    url: "/select/test",
    method: "post",
    data: {
      page: page1.value,
      limit: limit1.value,
      testName: testName.value,
      testNumber: testNumber.value,
    },
  }).then((res) => {
    tableData1.value = res.data;
    if (res.data.length == 0) {
      return;
    }
    total1.value = res.data[0].total;
  });
};
const handleCurrentChange1 = (val: number) => {
  axios({
    url: "/get/Kh",
    method: "post",
    data: {
      page: page1.value,
      testName: testName.value,
      testNumber: testNumber.value,
    },
  }).then((res) => {
    tableData1.value = res.data;
    if (res.data.length == 0) {
      return;
    }
    total1.value = res.data[0].total;
  });
};
const handleSizeChange3 = (val: number) => {
  axios({
    url: "/get/Search/ywy",
    method: "post",
    data: {
      testName: testName.value,
      testNumber: testNumber.value,
      page: page3.value,
      limit: limit3.value,
    },
  }).then((res) => {
    tableData3.value = res.data;
    if (res.data.length == 0) {
      total3.value = 0;
      return;
    }
    total3.value = res.data[0].total;
  });
};
const handleCurrentChange3 = (val: number) => {
  axios({
    url: "/get/Search/ywy",
    method: "post",
    data: {
      testName: testName.value,
      testNumber: testNumber.value,
      page: page3.value,
      limit: limit3.value,
    },
  }).then((res) => {
    tableData3.value = res.data;
    if (res.data.length == 0) {
      total3.value = 0;
      return;
    }
    total3.value = res.data[0].total;
  });
};
const handleSizeChange4 = (val: number) => {
  axios({
    url: "/select/test",
    method: "post",
    data: {
      testName: testName.value,
      testNumber: testNumber.value,
      page: page4.value,
      limit: limit4.value,
    },
  }).then((res) => {
    tableData4.value = res.data;
    total4.value = res.data[0].total;
  });
};
const handleCurrentChange4 = (val: number) => {
  axios({
    url: "/select/test",
    method: "post",
    data: {
      testName: testName.value,
      testNumber: testNumber.value,
      page: page4.value,
      limit: limit4.value,
    },
  }).then((res) => {
    tableData4.value = res.data;
    total4.value = res.data[0].total;
  });
};
const handleSizeChange5 = (val: number) => {
  axios({
    url: "/select/test",
    method: "post",
    data: {
      testName: testName.value,
      testNumber: testNumber.value,
      page: page5.value,
      limit: limit5.value,
    },
  }).then((res) => {
    // tableData4.value = res.data;
    const testList = res.data;

    tableData5.value = testList.map((test) => ({
      // 根据 djzt 的值设置状态
      // 根据 djzt 的值设置状态
      zt: test.zt === 0 ? "待审" : "已审核",
      id: test.id,
      testName: test.testName,
      testNumber: test.testNumber,
    }));
    if (testList.length == 0) {
      total5.value = 0;
      return;
    }
    total5.value = res.data[0].total;
  });
};
const handleCurrentChange5 = (val: number) => {
  axios({
    url: "/select/test",
    method: "post",
    data: {
      testName: testName.value,
      testNumber: testNumber.value,
      page: page5.value,
      limit: limit5.value,
    },
  }).then((res) => {
    // tableData4.value = res.data;
    const testList = res.data;
    tableData5.value = testList.map((test) => ({
      // 根据 djzt 的值设置状态
      // 根据 djzt 的值设置状态
      zt: test.zt === 0 ? "待审" : "已审核",
      autoId: test.autoId,
      testName: test.testName,
      testNumber: test.testNumber,
    }));
    if (testList.length == 0) {
      total5.value = 0;
      return;
    }
    total5.value = res.data[0].total;
  });
};
// 新增
const insertMaterialsFixed = () => {
  const userName = Cookies.get("userName");
  if (!userName) {
    router.push("/");
    return;
  }
  // if (form.djrq == "") {
  //   ElMessage({
  //     showClose: true,
  //     message: "单据日期未填写",
  //     type: "error",
  //   });
  //   return;
  // }
  // if (form.bzfa == "") {
  //   ElMessage({
  //     showClose: true,
  //     message: "标准方案未填写",
  //     type: "error",
  //   });
  //   return;
  // }
  // if (form.ddsl == "") {
  //   ElMessage({
  //     showClose: true,
  //     message: "订单数量未填写",
  //     type: "error",
  //   });
  //   return;
  // }
  // 显示确认弹窗
  ElMessageBox.confirm("确认保存吗？", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {});
  axios({
    url: "/insert/test",
    method: "post",
    data: {
      testName: form.testName,
      testNumber: form.testNumber,
      isDel: 0,
    },
  })
    .then((res) => {
      if (res.data.code == 200) {
        // location.reload();
        ElMessage({
          showClose: true,
          message: "保存成功",
          type: "success",
        });
        OFFdialogTableVisible();
        selectpurposes();
        return;
      }
      ElMessage({
        showClose: true,
        message: "保存失败",
        type: "error",
      });
    })
    .catch(() => {});
};
const exportToPdf = () => {
  if (selectedRows.value.length === 0) {
    alert("请选择要导出的数据");
    return;
  }
  // 创建一个jsPDF实例
  const pdf = new jsPDF();

  // 设置表格标题
  const title = "表格数据导出";
  pdf.setFontSize(16);
  pdf.text(title, 10, 10);

  // 设置表格头部
  const headers = ["ID", "测试名称", "测试数字"];
  const headerRows = [];
  headers.forEach((header, index) => {
    headerRows.push({ name: header, dataKey: index.toString() });
  });

  // 设置被选择的行数据
  const selectedData = [];
  selectedRows.value.forEach((row) => {
    const rowData = [];
    rowData.push(row.id);
    rowData.push(row.testName);
    rowData.push(row.testNumber);
    selectedData.push(rowData);
  });

  // 将被选择的行添加到 PDF 中
  pdf.autotable({
    startY: 20,
    head: [headerRows],
    body: selectedData,
  });

  // 保存或下载PDF文件
  pdf.save("exported-file.pdf");
};
const fileList = ref([]);
// 上传成功之后的回调函数
const handleExceed = (files: Array<any>, fileList: Array<any>) => {
  ElMessage.warning("超出文件数量限制，请删除部分文件后再试！");
};
const beforeUpload = (file: File) => {
  const isLt2M = file.size / 1024 / 1024 < 2; // 2MB
  if (!isLt2M) {
    alert("上传文件大小不能超过 2MB!");
  }
  return isLt2M;
};
const handleSuccess = (response: any, file: File, fileList: Array<any>) => {
  console.log("上传成功，服务器返回的数据：", response);
  console.log("response.code 的值：", response.code);
  // 假设后端返回的数据结构中有一个名为 code 的字段表示状态码
  if (response.code == 200) {
    alert("上传成功！");
    selectpurposes();
  } else if (response.code == 501) {
    alert("不要重复上传文件！");
    // 处理上传失败后的逻辑
  } else if (response.code == 502) {
    alert("不要上传空白文件！");
  } else {
    console.log("文件上传失败，服务器返回错误码：", response.code);
    alert("文件上传失败!");
  }
};
const downloadFile = () => {
  if (selectedRows.value.length === 1) {
    // 在这里执行删除选中行的逻辑，可以使用 selectedRows.value[0] 获取唯一选中的一行
    ElMessageBox.confirm("确认下载吗？", "提示", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(() => {
        console.log("确认按钮被点击");
        console.log(selectedRows.value);
        const userName = Cookies.get("userName");
        axios({
          url: "/download",
          method: "post",
          data: {
            // uploader:userName
            fileName: selectedRows.value[0].fileName,
            filePath: selectedRows.value[0].filePath,
          },
          responseType: "blob",
        }).then((res) => {
          console.log(res.data);
          if (res.status === 200) {
            // 创建 Blob 对象
            const blob = new Blob([res.data], { type: res.headers["content-type"] });
            // 创建下载链接
            const url = window.URL.createObjectURL(blob);
            const link = document.createElement("a");
            link.href = url;
            // 设置下载文件名
            link.setAttribute("download", "测试");
            // 添加链接到页面并触发点击
            document.body.appendChild(link);
            link.click();
            // 移除链接并释放 URL 对象
            document.body.removeChild(link);
            window.URL.revokeObjectURL(url);
            alert("下载成功！");
            // ElMessage({
            //   showClose: true,
            //   message: res.data,
            //   type: "success",
            // });
            selectpurposes();
            // searchButton();
            return;
          }
          alert("下载失败！");
          // ElMessage({
          //   showClose: true,
          //   message: res.data.data,
          //   type: "error",
          // });
        });
      })
      .catch(() => {});
  } else {
    ElMessage.warning("请选择一行进行下载操作");
  }
};
const deleteFile = () => {
  if (selectedRows.value.length === 1) {
    // 在这里执行删除选中行的逻辑，可以使用 selectedRows.value[0] 获取唯一选中的一行
    ElMessageBox.confirm("确认删除吗？", "提示", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(() => {
        console.log(selectedRows.value);
        const userName = Cookies.get("userName");
        axios({
          url: "/del/upload",
          method: "post",
          data: {
            // uploader:userName
            id: selectedRows.value[0].id,
            filePath: selectedRows.value[0].filePath,
          },
        }).then((res) => {
          if (res.status == 200) {
            alert("删除成功！");
            // ElMessage({
            //   showClose: true,
            //   message: res.data,
            //   type: "success",
            // });
            selectpurposes();
            // searchButton();
            return;
          }
          alert("删除失败！");
          // ElMessage({
          //   showClose: true,
          //   message: res.data.data,
          //   type: "error",
          // });
        });
      })
      .catch(() => {});
  } else {
    ElMessage.warning("请选择一行进行删除操作");
  }
};
// 下载文件
// const downloadFile = async (row) => {
//     // console.log(row)
//     const { download_number, id } = row  					// 从行中获取下载文件接口的传入参数
//     await updateDownloadTimesAPI({ download_number, id })  	// 调用下载文件的接口
//     const url = row.file_url  								// 从行数据中获取下载链接
//     const link = document.createElement('a')				// 创建链接标签，即a标签，并将dom命名为link
//     link.href = url											// 为dom为link的元素添加链接
//     link.setAttribute('download', '')						// 为link设置下载属性
//     document.body.appendChild(link)							// 把创建并配置好的link dom添加到页面文档中
//     link.click()											// 模拟dom的点击事件
//     document.body.removeChild(link)							// 从文档中移出link节点
//     getCurrentPageData()									// 调用写好的方法刷新数据
// };
// const getCurrentPageData = async () => {
//     const res = await returnFileListDataAPI({ page: paginationData.value.currentPage - 1 })
//     res.forEach(item => {
//         item.upload_time = item.upload_time?.slice(0, 19)
//         item.file_size = Math.floor(item.file_size) + 'kb'
//     })
//     tableData.value = res
// }

//审核
const handleWarning0 = () => {
  if (selectedRows.value.length === 1) {
    // 在这里执行删除选中行的逻辑，可以使用 selectedRows.value[0] 获取唯一选中的一行
    ElMessageBox.confirm("确认审核吗？", "提示", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(() => {
        const userName = Cookies.get("userName");
        const currentFormattedDateTime = getCurrentFormattedDateTime();

        axios({
          url: "/update/zt",
          method: "post",
          data: {
            shr: userName,
            autoId: selectedRows.value[0].autoId,
            zt: 2,
            shsj: currentFormattedDateTime,
          },
        }).then((res) => {
          if (res.data.code == 200) {
            ElMessage({
              showClose: true,
              message: res.data.data,
              type: "success",
            });
            selectpurposes();
            return;
          }
          ElMessage({
            showClose: true,
            message: res.data.data,
            type: "error",
          });
        });
      })
      .catch(() => {});
  } else {
    ElMessage.warning("请选择一行进行审核操作");
  }
};
const printPage = () => {
  // 使用 window.print() 方法触发页面打印
  isPrinting.value = true;

  // Use the browser's print functionality
  window.print();

  // Reset the flag after printing is done
  isPrinting.value = false;
};
//弃审
// const handleWarning1 = () => {
//   if (selectedRows.value.length === 1) {
//     // 在这里执行删除选中行的逻辑，可以使用 selectedRows.value[0] 获取唯一选中的一行

//     ElMessageBox.confirm("确认弃审吗？", "提示", {
//       confirmButtonText: "确认",
//       cancelButtonText: "取消",
//       type: "warning",
//     })
//       .then(() => {
//         const userName = Cookies.get("userName");
//         const currentFormattedDateTime = getCurrentFormattedDateTime();
//         axios({
//           url: "/update/zt",
//           method: "post",
//           data: {
//             userName: userName,
//             autoId: selectedRows.value[0].autoId,
//             zt: 3,
//             shsj: currentFormattedDateTime,
//           },
//         }).then((res) => {
//           if (res.data.code == 200) {
//             // location.reload();
//             ElMessage({
//               showClose: true,
//               message: res.data.data,
//               type: "success",
//             });
//             selectpurposes();
//             return;
//           }
//           ElMessage({
//             showClose: true,
//             message: res.data.data,
//             type: "error",
//           });
//         });
//       })
//       .catch(() => {});
//   } else {
//     ElMessage.warning("请选择一行进行审核操作");
//   }
// };

//更新
const updatYwy = () => {
  axios({
    // url: "/get/ywy",
    url: "/insert/test",
    method: "post",
    data: {
      testName: testName.value,
      testNumber: testNumber.value,
      isDel: 0,
      page: page3.value,
      limit: limit3.value,
    },
  }).then((res) => {
    ElMessageBox.confirm("确认更新吗？", "提示", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(() => {
        if (res.data.code == 200) {
          ElMessage({
            showClose: true,
            message: res.data.data,
            type: "success",
          });
          getYwy();
          return;
        }
        ElMessage({
          showClose: true,
          message: res.data.data,
          type: "error",
        });
      })
      .catch(() => {});
  });
};
const handleDeletes = (index: number) => {
  formDataList.value.splice(index, 1);
  if (formDataList.value.length === 0) {
    addRow();
  }
};
//删除已勾选
const getDeleteRowData = () => {
  const selectedIndexes: any = [];

  // 找到已勾选行的索引
  formDataList.value.forEach((formData, index) => {
    if (formData.selected) {
      selectedIndexes.push(index);
    }
  });

  // 删除已勾选行
  for (let i = selectedIndexes.length - 1; i >= 0; i--) {
    formDataList.value.splice(selectedIndexes[i], 1);
  }

  // 如果没有剩余行数据，添加一行
  if (formDataList.value.length === 0) {
    addRow();
  }
  selectAll.value = false;
};
const toggleSelectAll = () => {
  for (const formData of formDataList.value) {
    formData.selected = selectAll.value === true;
  }
};
const handleDelete = () => {
  if (selectedRows.value.length === 1) {
    // 在这里执行删除选中行的逻辑，可以使用 selectedRows.value[0] 获取唯一选中的一行
    ElMessageBox.confirm("确认删除吗？", "提示", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(() => {
        const userName = Cookies.get("userName");
        axios({
          url: "/del/test",
          method: "post",
          data: {
            autoId: selectedRows.value[0].autoId,
          },
        }).then((res) => {
          if (res.data.code == 200) {
            ElMessage({
              showClose: true,
              message: res.data.data,
              type: "success",
            });
            // selectpurposes();
            searchButton();
            return;
          }
          ElMessage({
            showClose: true,
            message: res.data.data,
            type: "error",
          });
        });
      })
      .catch(() => {});
  } else {
    ElMessage.warning("请选择一行进行删除操作");
  }
};

// 方法：获取已勾选数据
const getSelectedRowsData = () => {
  const selectedData = formDataList.value.filter((formData) => formData.selected);
  // 在这里可以执行想要的操作，例如将 selectedData 发送到服务器或者在控制台中打印出来
};
const RowClick = (row, selection) => {
  table.value.toggleRowSelection(row);
};
//导出数据

const exportSelectedData = () => {
  console.log(selectedRows.value);

  if (selectedRows.value.length === 0) {
    alert("请选择要导出的数据");
    return;
  }

  if (selectedRows.value.length === 1) {
    // 提示用户是否导出数据
    const confirmExport = window.confirm("是否导出数据？");
    if (!confirmExport) {
      return;
    }
  }

  const headerTranslations = {
    fileName: "文件名",
    fileType: "文件类型",
    formattedFileSize: "文件大小",
    // 添加更多的映射...
  };

  // 将英文标头转换为中文标头
  const translatedHeaders = Object.keys(selectedRows.value[0]).map(
    (header) => headerTranslations[header] || header
  );

  // 将数据转换为适用于 Excel 的格式
  const dataForExcel = selectedRows.value.map((row) => {
    const translatedRow = {};
    Object.keys(row).forEach((key) => {
      translatedRow[headerTranslations[key] || key] = row[key];
    });
    return translatedRow;
  });

  // 创建工作表
  const worksheet = XLSX.utils.json_to_sheet(dataForExcel, { header: translatedHeaders });
  const workbook = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(workbook, worksheet, "Sheet 1");

  // 使用setTimeout确保在异步任务队列中执行
  setTimeout(() => {
    XLSX.writeFile(workbook, "exported_data.xlsx");
  }, 0);
};
//导入数据
const fileInputRef = ref<HTMLInputElement | null>(null);
const importedRows = ref<any[]>([]);
const headerTranslations = {
  zt: "状态",
  testName: "测试名称",
  testNumber: "测试数字",
  // 添加更多的映射...
};
const handleFileChange = (event: Event) => {
  const fileInput = fileInputRef.value;

  if (fileInput && fileInput.files) {
    const file = fileInput.files[0];
    readExcelFile(file);
  }
};

const readExcelFile = (file: File) => {
  const reader = new FileReader();

  reader.onload = (e) => {
    const data = new Uint8Array(e.target.result);
    const workbook = XLSX.read(data, { type: "array" });

    const sheetName = workbook.SheetNames[0];
    const worksheet = workbook.Sheets[sheetName];

    const importedData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });

    const englishHeaders = importedData[0].map((header: string) => {
      // 假设有一个 headerTranslations 对象来映射中文标头到英文标头
      for (const engHeader in headerTranslations) {
        if (headerTranslations[engHeader] === header) {
          return engHeader;
        }
      }
      return header;
    });

    const rows = importedData.slice(1).map((row: any[]) => {
      const rowData: Record<string, any> = {};
      row.forEach((cell, index) => {
        rowData[englishHeaders[index]] = cell;
      });
      return rowData;
    });

    // 更新导入的数据
    importedRows.value = rows;
  };

  reader.readAsArrayBuffer(file);
};
// 获取当前时间
const getCurrentFormattedDateTime = () => {
  const currentDateTime = new Date();

  // 格式化当前时间
  const formattedDateTime = currentDateTime.toLocaleString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
    second: "2-digit",
  });
  // const formattedDateTime = format(currentDateTime, "YYYY-MM-dd HH:mm:ss");

  return formattedDateTime;
};
// 获取年月日
const getCurrentFormattedDate = () => {
  const currentDateTime = new Date();

  // 格式化当前时间，只获取年月日
  const formattedDate = currentDateTime.toLocaleString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
  });

  return formattedDate;
};
selectpurposes();
interface Tree {
  label: string;
  children?: Tree[];
}
</script>

<style scoped>
@media print {
  body * {
    visibility: hidden;
  }
  .print-template,
  .print-template * {
    visibility: visible;
  }
  .print-template {
    position: absolute;
    left: -200px; /* Adjust left value to move the table to the left */
    top: 0;
    width: 100%;
  }
  /* .el-table__header-wrapper {
    display: none !important;
  } */

  /* 隐藏分页 */
  .demo-pagination-block {
    display: none !important;
  }

  /* 调整表格的位置，确保表格主体在纸张内 */
  .el-table__body-wrapper {
    margin-top: 0rem; /* 调整表格与纸张顶部的距离 */
  }
  .el-table__column--selection {
    display: none !important;
  }

  /* 将其他列向前移动一格 */
  /* .el-table__body td:nth-child(2), .el-table__header th:nth-child(2) {
  display: none !important; 
  }隐藏第二列 */

  /* .el-table__body {
  border: none !important;
} */

  /* 隐藏表格单元格的边框 */
  .el-table__body tr {
    border: none !important;
  }

  /* 隐藏表格单元格的格子 */
  /* .el-table__body td, .el-table__body th {
  border: none !important;
} */
  /* 根据需要添加更多打印样式 */
}
/* 悬停 */
/* #f9f9fc, #fef5f0 */
.el-table {
  /* --el-table-row-hover-bg-color: rgba(0, 158, 250, 0.219) !important; */
  /* --el-table-row-hover-bg-color: #fef5f0 !important; */
  --el-table-row-hover-bg-color: rgba(254, 245, 240, 0.8) !important;
}
/* 选中 */
.el-table {
  /* --el-table-row-hover-bg-color: #fef5f0 !important; */
  --el-table-row-hover-bg-color: rgba(254, 245, 240, 0.8) !important;
}

.custom-dialog {
  position: fixed;
  top: 12%;
  left: 50%;
  width: 20%;
  /* 其他样式... */
}

.vertical-line2 {
  width: 100%; /* 让横线的宽度与整个页面宽度一致 */
  height: 2px;
  left: 0;
  background-color: #d3d5d7; /* 横线的颜色，可以根据你的需求修改 */
  position: fixed;
  top: 0; /* 设置横线的垂直位置，可以根据你的布局调整 */
}

.vertical-line3 {
  width: 100%; /* 让横线的宽度与整个页面宽度一致 */
  height: 1px;
  background-color: #d3d5d7; /* 横线的颜色，可以根据你的需求修改 */
  position: fixed;
  top: 4.5%; /* 设置横线的垂直位置，可以根据你的布局调整 */
  left: 0%;
}
.title {
  font-size: 18px;
}
.demo-pagination-block {
  float: right;
}
::v-deep .el-table .cell {
  padding: 0;
}
::v-deep .el-header {
  padding: 0;
}
.my-header {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}
.buttonHeard {
  position: absolute;
  top: 0%;
  right: 1%;
}
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.my-header {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}

.lab {
  background-color: rgba(247, 247, 247, 0.903);
  /* border-radius: 5px; */
  text-align: center;
  margin-bottom: 0px;
  text-align: right;
}

.labs {
  margin-bottom: 0px;
}
/* 子表 */
.sticky-header {
  position: sticky;
  top: -1px;
  background-color: #ddd;
}

.table-header {
  border: 1px solid #ccc;
  background: rgb(225, 225, 230);
  /* width: 50px; */
  z-index: 99;
}

table tr td {
  /* width: 50px; */
  /* width: 10vh; */
  height: 30px;
}

table {
  border-collapse: collapse;
  border: 1px solid #ccc;
  width: 100%;
}

input {
  border: 1px solid transparent;
}

td {
  border: 1px solid #ccc;
}
#buttonmForm {
  position: absolute;
  bottom: 3px;
}
.vertical-line2 {
  width: 100%; /* 让横线的宽度与整个页面宽度一致 */
  height: 1px;
  background-color: #d3d5d7; /* 横线的颜色，可以根据你的需求修改 */
  position: fixed;
  top: 4.4%; /* 设置横线的垂直位置，可以根据你的布局调整 */
}
.--el-dialog-padding-primary {
  padding: 0;
}
.table-value:hover {
  cursor: pointer;
  z-index: 11;
}
.red-asterisk {
  position: relative;
}
.red-asterisk::before {
  content: "*";
  color: red;
  /* position: absolute;
  left: 5px;
  top: 10px;
  margin-right: 4px; */
}
.dialogDiv {
  position: relative;
  top: 10px;
}
.flex-grow {
  flex-grow: 1;
}
.demo-basic .block:not(:last-child) {
  border-right: 1px solid var(--el-border-color);
}
.demo-basic .block {
  flex: 1;
}
::-webkit-scrollbar {
  width: 5px;
}
</style>
